<?php
namespace Model;

use Lib\Http\Cookie;
use Dao, Lib\Http\Form, Lib\Http\Request;

class Domain {
	/**
	 * Dao\Domain
	 * @var Dao\Domain
	 */
	private $DDomain = NULL;

	public function __construct() {
		$this->DDomain = new \Dao\Domain();
	}

	public function make($min, $max) {
		$domain = '';
		
		$length = mt_rand($min, $max);
		
		$vowels = array('a', 'e', 'i', 'o', 'u');
		
		$letter = array();
		
		for ($i = 0; $i < $length; $i++) {
			for ($j = 0; $j < 1000; $j++) {
				while (TRUE) {
					if ($i == $length - 1) {
						$k = array_rand($vowels);
						$char = $vowels[$k];
					} else {
						$char = chr(mt_rand(97, 122));
					}
					
					if ($i > 0 && !in_array($char, $vowels) && !in_array($domain[$i - 1], $vowels)) {
						continue;
					}
					
					break;
				}
				
				if (in_array($char, $letter) || $i <= 4) {
					break;
				}
			}
			
			$domain .= $char;
		}
		
		$result = $this->DDomain->select(array('name' => $domain));
		if ($result->count > 0) {
			return $this->make($min, $max);
		}
		
		return $domain;
	}

	public function create($domain) {
		if (count($domain) < 1) {
			return FALSE;
		}
		
		try {
			$result = $this->search($domain);
		} catch (\Exception $e) {
			return $e->getMessage();
		}
		
		foreach ($result as $k => $v) {
			$this->DDomain->insert(array('live' => $v ?  : 0, 'name' => $k));
		}
		
		return TRUE;
	}

	public function sync($domain) {
		if (count($domain) < 1) {
			return FALSE;
		}
		
		try {
			$result = $this->search($domain);
		} catch (\Exception $e) {
			return $e->getMessage();
		}
		
		foreach ($result as $k => $v) {
			$this->DDomain->update(array('live' => $v ?  : 0, 'marktime' => date('Y-m-d H:i:s')), array('name' => $k));
		}
		
		return TRUE;
	}

	public function well($domain) {
		return $this->DDomain->update(array('well' => 1), array('name' => $domain));
	}

	public function fetch($well = TRUE) {
		return $this->DDomain->select(array('well' => $well == TRUE ? 1 : 0, 'live' => 1), array('marktime'));
	}

	public function clean($domain = NULL) {
		if ($domain) {
			return $this->DDomain->update(array('live' => 0), array('name' => $domain));
		}
		
		return $this->DDomain->update(array('live' => 0), array('well' => 0));
	}

	private function search($domain) {
		$Form = new Form();
		$Cookie = Cookie::getInstance('http://www.name.com/');
		$Request = new Request();
		
		$Cookie->option(Cookie::OPT_STORAGE, Cookie::COOKIE_STORAGE_FILES);
		
		$Request->option(Request::OPT_MODE, Request::OPT_MODE_SOCKET);
		$Request->option(Request::OPT_TIMEOUT, 5);
		$Request->option(Request::OPT_READ_TIMEOUT, 10);
		
		// ======================================================
		$Response = $Request->get('http://www.name.com/names', NULL, $Cookie);
		if (!preg_match('/name=\'bsab\' value="(\w+)"/', $Response, $bsab)) {
			if (is_object($Response) && $Response->status() == '200') {
				throw new \Exception("Fetch 'bsab' Error, Response is " . $Response);
			}
			
			return [];
		}
		
		// ======================================================
		$Form->set('bsab', $bsab[1]);
		$Form->set('domain', implode("\r\n", $domain));
		$Form->set('opttldarray[]', 'com');
		
		$Response = $Request->post('http://www.name.com/names', $Form, $Cookie);
		if (!preg_match('/\?get_results=(\w+)/', $Response, $x)) {
			if (is_object($Response) && $Response->status() == '200') {
				throw new \Exception('Cannot initialized result id, Response is ' . $Response);
			}
			
			return [];
		}
		
		// ======================================================
		$Response = $Request->get("http://www.name.com/javascript/search/bulk_search.php?get_results={$x[1]}&noforward=true");
		$result = explode(';', $Response);
		if (substr($result[0], 0, 4) != 'code' || end($result) != 'done') {
			if (is_object($Response) && $Response->status() == '200') {
				throw new \Exception('Parse result fail, Response is ' . $Response);
			}
			
			return [];
		}
		
		unset($result[0]);
		array_pop($result);
		
		// ======================================================
		$domain = [];
		
		foreach ($result as $v) {
			$v = explode(',', $v);
			$x = pathinfo($v[0]);
			$domain[$x['filename']] = $v[1] == 1;
		}
		
		return $domain;
	}
}